﻿using nhCore.db;
using nhFormLib;
using Sunny.UI;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Windows.Forms;

namespace envG.hmi
{
    public partial class FormHMI太空舱 : UIForm
    {
        public FormHMI太空舱()
        {
            InitializeComponent();

            WindowState = FormWindowState.Maximized;

            SlUi.FindControl<Control>(this).ForEach(x => x.ContextMenuStrip = UiContextMenuStrip设置);
            颜色初始化();
            管道控件分类();
            System.Windows.Forms.Timer time = new();
            time.Tick += new EventHandler(OnTimerShow);
            time.Interval = 500;
            time.Start();
        }

        #region 管道
        private Dictionary<int, List<UIPipe>> Dic管道 = [];
        private Dictionary<int, List<UIValve>> Dic阀门 = [];
        private int _通道 = 1;
        private int _second = 20;
        private readonly Color _color阀门把手关 = Color.Red;
        private readonly Color _color阀门把手开 = Color.ForestGreen;
        private readonly Color _color阀门关 = Color.White;
        private Color _color阀门开 = Color.Purple;
        private void 管道控件分类()
        {
            Dic管道 = SlUi.ListToDictionary(SlUi.FindControl<UIPipe>(this));
            var valves = SlUi.FindControl<UIValve>(this);
            valves.ForEach(x => x.ValveColor = _color阀门把手关);
            Dic阀门 = SlUi.ListToDictionary(valves);
            foreach (var kv in Dic阀门.Where(x => x.Key >= 5))
            {   //对换气阀门设置
                foreach (var valve in kv.Value)
                {
                    valve.Click += Valve_Click;
                }
            }
        }

        private void Valve_Click(object? sender, EventArgs e)
        {
            if (sender is not UIValve valve) { return; }

            bool isActive = valve.FillColor == _color阀门关;
            //Color color = valve.Active ?
            //    _color阀门把手开 : _color阀门把手关;

            if (TagToInt(valve.Tag, NumberStyles.HexNumber) is int tag && Dic阀门.TryGetValue(tag, out var valves))
            {
                valves.ForEach(x =>
                {
                    x.Active = isActive;
                    x.ValveColor = isActive ? _color阀门把手开 : _color阀门把手关;
                    x.FillColor = isActive ? _color阀门开 : _color阀门关;
                });

                if (Dic管道.TryGetValue(tag, out var pipes))
                {
                    pipes.ForEach(x => x.Active = isActive);
                }
            }
        }


        /// <summary>
        /// 500ms刷新，每10秒轮换测量
        /// </summary>
        /// <param name="myObject"></param>
        /// <param name="myEventArgs"></param>
        private void OnTimerShow(Object? myObject, EventArgs myEventArgs)
        {
            Refresh();
            _second++;

            if (_second <= 20) { return; }
            _second = 0;

            foreach (var kv in Dic管道)
            {
                if (kv.Key > 4) { continue; }
                bool isActive = kv.Key == _通道;
                kv.Value.ForEach(x => x.Active = isActive);
                if (Dic阀门.TryGetValue(kv.Key, out var valves))
                {
                    valves.ForEach(x =>
                    {
                        x.ValveColor = isActive ? _color阀门把手开 : _color阀门把手关;
                        x.FillColor = isActive ? _color阀门开 : _color阀门关;
                        x.Active = isActive;
                    });
                }
            }
            if (_通道++ == 4) { _通道 = 1; }
        }
        #endregion

        /// <summary>
        /// Tag转Int
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="numberStyles">默认整型</param>
        /// <returns></returns>
        public static int? TagToInt(object? tag, NumberStyles numberStyles = NumberStyles.Integer)
        {
            int? ret = null;
            switch (tag)
            {
                case string:
                    if (int.TryParse(tag as string, numberStyles, CultureInfo.InvariantCulture, out var h))
                    {
                        ret = h;
                    }
                    break;

                case int:
                    ret = (int)tag;
                    break;
            }

            //if (tag is string str && int.TryParse(str, numberStyles, CultureInfo.InvariantCulture, out var h))
            //{
            //    ret = h;
            //}
            return ret;
        }

        #region 颜色
        private const string con_窗体背景色 = "窗体背景色";
        private const string con_外框边框色 = "舱框边框色";
        private const string con_内框边框色 = "舱体边框色";
        private const string con_内框背景色 = "舱体背景色";
        private const string con_气体颜色 = "气体颜色";
        private const string con_文字颜色 = "文字颜色";
        private const string con_文字背景色 = "文字背景色";
        private const string con_字体 = "字体";
        private void 颜色初始化()
        {

            if (NSetting.Singleton.ReadValue(con_窗体背景色) is string colorString)
            {
                try
                {
                    BackColor = ColorTranslator.FromHtml(colorString);
                }
                catch (Exception) { }
            }

            try
            {
                设置UIPanel边框色(
                    ColorTranslator.FromHtml(
                        NSetting.Singleton.ReadValue(con_外框边框色)
                        ?? ColorTranslator.ToHtml(Color.DarkBlue))
                    , 0);
            }
            catch (Exception) { }

            try
            {
                设置气体颜色(
                    ColorTranslator.FromHtml(
                        NSetting.Singleton.ReadValue(con_气体颜色)
                        ?? ColorTranslator.ToHtml(Color.Purple)));
            }
            catch (Exception) { }

            try
            {
                设置UIPanel边框色(
                    ColorTranslator.FromHtml(
                        NSetting.Singleton.ReadValue(con_内框边框色)
                        ?? ColorTranslator.ToHtml(Color.DarkBlue))
                    , 1);
            }
            catch (Exception) { }

            try
            {
                设置内框背景色(
                    ColorTranslator.FromHtml(
                        NSetting.Singleton.ReadValue(con_内框背景色)
                        ?? ColorTranslator.ToHtml(Color.Moccasin)));
            }
            catch (Exception) { }

            try
            {
                设置文字背景色(
                    ColorTranslator.FromHtml(
                        NSetting.Singleton.ReadValue(con_文字背景色)
                        ?? ColorTranslator.ToHtml(Color.WhiteSmoke)));
            }
            catch (Exception) { }

            try
            {
                设置文字颜色(
                    ColorTranslator.FromHtml(
                        NSetting.Singleton.ReadValue(con_文字颜色)
                        ?? ColorTranslator.ToHtml(Color.Black)));
            }
            catch (Exception) { }

            try
            {
                设置字体(
                    (Font)new FontConverter().ConvertFromString(
                        NSetting.Singleton.ReadValue(con_字体)
                        ?? string.Empty)!);
            }
            catch (Exception) { }
        }

        private void ToolStripMenuItem窗体背景色_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new()
            {
                Color = BackColor
            };
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                BackColor = colorDialog.Color;
                NSetting.Singleton.SetValue(con_窗体背景色, ColorTranslator.ToHtml(colorDialog.Color));
            }
        }

        private void ToolStripMenuItem外框边框色_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new();
            if (colorDialog.ShowDialog() == DialogResult.OK
                && sender is ToolStripMenuItem menuItem
                && TagToInt(menuItem.Tag) is int tag)
            {
                设置UIPanel边框色(colorDialog.Color, tag);
                NSetting.Singleton.SetValue(tag == 0 ? con_外框边框色 : con_内框边框色, ColorTranslator.ToHtml(colorDialog.Color));
            }
        }

        /// <summary>
        /// 设置UIPanel边框色
        /// </summary>
        /// <param name="color">设置颜色</param>
        /// <param name="tag">0为外框，1为内框</param>
        private void 设置UIPanel边框色(Color color, int tag)
        {
            SlUi.ListToDictionary(SlUi.FindControl<UIPanel>(this))[tag]
                .ForEach(x => x.RectColor = color);
        }

        private void ToolStripMenuItem气体颜色_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                设置气体颜色(colorDialog.Color);
                NSetting.Singleton.SetValue(con_气体颜色, ColorTranslator.ToHtml(colorDialog.Color));
            }
        }

        private void 设置气体颜色(Color color)
        {
            SlUi.FindControl<UIPipe>(this)
                .ForEach(x => x.FlowColor = color);
            _color阀门开 = color;
        }

        private void ToolStripMenuItem内框背景色_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                设置内框背景色(colorDialog.Color);
                NSetting.Singleton.SetValue(con_内框背景色, ColorTranslator.ToHtml(colorDialog.Color));
            }
        }

        private void 设置内框背景色(Color color)
        {
            SlUi.ListToDictionary(SlUi.FindControl<UIPanel>(this))[1]
                .ForEach(x => x.FillColor = color);
        }

        private void ToolStripMenuItem文字背景色_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new()
            {
                Color = SlUi.FindControl<UILabel>(this).First().BackColor,
            };
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                设置文字背景色(colorDialog.Color);
                NSetting.Singleton.SetValue(con_文字背景色, ColorTranslator.ToHtml(colorDialog.Color));
            }
        }

        private void 设置文字背景色(Color color)
        {
            (SlUi.FindControl<UILabel>(this))
                .ForEach(x => x.BackColor = color);
        }

        private void ToolStripMenuItem文字颜色_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new()
            {
                Color = SlUi.FindControl<UILabel>(this).First().ForeColor,
            };
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                设置文字颜色(colorDialog.Color);
                NSetting.Singleton.SetValue(con_文字颜色, ColorTranslator.ToHtml(colorDialog.Color));
            }
        }

        private void 设置文字颜色(Color color)
        {
            SlUi.FindControl<UILabel>(this)
                .ForEach(x => x.ForeColor = color);
        }

        private void ToolStripMenuItem字体_Click(object sender, EventArgs e)
        {
            FontDialog fontDialog = new()
            {
                Font = SlUi.FindControl<UILabel>(this).First().Font,
            };
            if (fontDialog.ShowDialog() == DialogResult.OK)
            {
                设置字体(fontDialog.Font);
                NSetting.Singleton.SetValue(con_字体, new FontConverter().ConvertToString(fontDialog.Font) ?? string.Empty);
            }
        }

        private void 设置字体(Font font)
        {
            SlUi.FindControl<UILabel>(this)
                .ForEach(x => x.Font = font);
        }
        #endregion
    }
}
